#include "SdkCheckInDls.h"
#include "InSdkSetNtpTime.h"

#define DEF_TAG "TYDls"

Com_pvoid SdkCheckInDls_Thread(Com_pvoid arg)
{
    while (g_ComThread_Running)
    {
        BOOL_T isDls = FALSE;
        TIME_T time_utc = 0;
        INT_T time_zone = 0;
        OPERATE_RET ret = 1;
        struct timeval set_time;

        if ((Ext_InComFile_Access(DEF_FLAG_MQTT_OFFLINE) == DEF_COM_FILE_EXIST) &&
            g_ComThread_Running)
        {
            sleep(1);
            continue;
        }

        memset(&set_time, 0, sizeof(set_time));

        while ((ret != OPRT_OK) && g_ComThread_Running)
        {
            ret = tuya_ipc_get_service_time_force(&time_utc, &time_zone);
            usleep(100 * 1000);
        }

        tuya_ipc_check_in_dls(time_utc, &isDls);
        if (TRUE == isDls)
        {
            time_zone += 3600;
        }
        Ext_InComTimer_SetTZSec(time_zone);
        PRT_DBG(DEF_TAG, "utc: %d,dls: %d,tz: %d\n", time_utc, isDls, time_zone);

        //  Setting the time using the system interface such as settimeofday;
        /* 1577808000 is 2020-01-01 00:00:00 */
        if (time_utc <= 1577808000)
        {
            PRT_WARN(DEF_TAG, "use time.windows.com\n");
            time_zone = 0;
            Ext_InComTimer_SetTZSec(time_zone);
            char hostname[] = "time.windows.com";
            Ext_InSdkNtp_SetTime(time_zone, hostname);
        }
        else
        {
            set_time.tv_sec = time_utc + time_zone;
            while (g_ComThread_Running)
            {
                ret = settimeofday(&set_time, NULL);
                if (ret != 0)
                {
                    PRT_ERR(DEF_TAG, "tv_sec: %ld\n", set_time.tv_sec);
                    sleep(1);
                    set_time.tv_sec++;
                }
                else
                {
                    break;
                }
            }
        }

        sleep(10);
    }

    pthread_exit(0);
}

Com_void Ext_SdkCheckInDls_Init(Com_void)
{
    pthread_t id;

    pthread_create(&id, NULL, SdkCheckInDls_Thread, NULL);
    pthread_detach(id);
}
